from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_mysqldb import MySQL

app = Flask(__name__)
app.static_folder = r'E:\Vscode\project_student_management\apps\static'  # 设置静态文件目录
app.static_url_path = '/static'  # 设置静态文件url路径
app.template_folder = r"E:\Vscode\project_student_management\apps\veiw\templates"  # 设置模板文件目录

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'login_system'

mysql = MySQL(app)

@app.route('/')
def index():
    return render_template('login.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username == 'admin' and password == '123456':
            # 登录成功，重定向到首页
            return redirect(url_for('student_management'))
        else:
            return render_template("error.html", name = "用户名或密码错误！")
    else:
        username = request.args.get('username')
        return render_template("hello.html", username)
  

@app.route('/addstudent')
def jump_to_add_student():
    return render_template("add_student.html")


@app.route('/student_management')
def student_management():
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT * FROM students")
    students = cursor.fetchall()
    print(students)
    return render_template('student_management.html', students=students)

# 分页查询
@app.route('/students', methods=['GET'])
def get_students():
    page = int(request.args.get('page', 1))
    per_page = 10
    start = (page - 1) * per_page
    query = "SELECT * FROM students LIMIT %s, %s"
    data = mysql.connection.cursor()
    data.execute(query, (start, per_page))
    students = data.fetchall()
    return jsonify(students)

# 添加学生信息
@app.route('/add_student', methods=['POST'])
def add_student():
    name = request.form['name']
    grade = request.form['grade']
    cursor = mysql.connection.cursor()
    cursor.execute("INSERT INTO students (name, grade) VALUES (%s, %s)", (name, grade))
    mysql.connection.commit()
    return redirect(url_for('student_management'))

# 删除学生信息
@app.route('/delete_student/<int:id>', methods=['POST'])
def delete_student(id):
    cursor = mysql.connection.cursor()
    cursor.execute("DELETE FROM students WHERE id = %s", (id,))
    mysql.connection.commit()
    return jsonify({'result': True})

# 批量删除学生信息
@app.route('/batch_delete_students', methods=['POST'])
def batch_delete_students():
    student_ids = request.form.getlist('student_ids[]')
    cursor = mysql.connection.cursor()
    cursor.execute("DELETE FROM students WHERE id IN (%s)" % ','.join(['%s'] * len(student_ids)), student_ids)
    mysql.connection.commit()
    return jsonify({'result': True})

# 修改学生信息
@app.route('/edit_student/<int:id>', methods=['GET', 'POST'])
def edit_student(id):
    if request.method == 'POST':
        name = request.form['name']
        grade = request.form['grade']
        cursor = mysql.connection.cursor()
        cursor.execute("UPDATE students SET name = %s, grade = %s WHERE id = %s", (name, grade, id))
        mysql.connection.commit()
        return redirect(url_for('student_management'))
    else:
        cursor = mysql.connection.cursor()
        cursor.execute("SELECT * FROM students WHERE id = %s", (id,))
        student = cursor.fetchone()
        return render_template('edit_student.html', student=student)

if __name__ == '__main__':
    app.run(debug=True)